package com.qwc.blog.web.admin;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qwc.blog.common.annotation.AdminController;
import com.qwc.blog.entity.Dynamic;
import com.qwc.blog.entity.dto.DynamicDto;
import com.qwc.blog.entity.dto.DynamicRequestDto;
import com.qwc.blog.service.IDynamicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 * 博主动态 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2022-03-08
 */
@Slf4j
@AdminController("dynamic")
public class DynamicController {

    @Autowired
    private IDynamicService dynamicService;

    @PostMapping
    public ResponseEntity<Object> add(@RequestBody DynamicDto dto) {
        Dynamic dynamic = new Dynamic();
        dynamic.setDynamic(dto.getContent());
        dynamic.setStatus(dto.getStatus());
        if (dto.isTop()){
            dynamic.setTopTime(new Date());
        }
        return ResponseEntity.ok(dynamicService.save(dynamic));
    }

    @GetMapping("page")
    public ResponseEntity<Object> page(DynamicRequestDto dto) {
        LambdaQueryWrapper<Dynamic> wrapper = Wrappers.<Dynamic>lambdaQuery()
                .eq(CharSequenceUtil.isNotBlank(dto.getStatus()), Dynamic::getStatus, dto.getStatus());
        if(CollUtil.isNotEmpty(dto.getDateRange())){
            wrapper.le(Dynamic::getCreateTime, dto.getDateRange().get(1))
                    .ge(Dynamic::getCreateTime, dto.getDateRange().get(0));
        }
        wrapper.orderByDesc(Arrays.asList(Dynamic::getTopTime,Dynamic::getCreateTime));
        return ResponseEntity.ok(dynamicService.page(dto, wrapper));
    }

    @PutMapping("/{id}/{status}")
    public ResponseEntity<Object> updateStatus(@PathVariable Integer id,@PathVariable String status){
        return ResponseEntity.ok(dynamicService.update(Wrappers.<Dynamic>lambdaUpdate()
                .set(Dynamic::getStatus,status).eq(Dynamic::getDynamicId,id)));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Object> deleteById(@PathVariable Integer id){
        return ResponseEntity.ok(dynamicService.removeById(id));
    }

    @PutMapping("/top/{id}/{status}")
    public ResponseEntity<Object> changeTop(@PathVariable Integer id,@PathVariable boolean status){
        if (status){
            return ResponseEntity.ok(dynamicService.update(Wrappers.<Dynamic>lambdaUpdate()
                    .set(Dynamic::getTopTime,new Date())
                    .eq(Dynamic::getDynamicId,id)));
        }
        return ResponseEntity.ok(dynamicService.update(Wrappers.<Dynamic>lambdaUpdate()
                .set(Dynamic::getTopTime,null)
                .eq(Dynamic::getDynamicId,id)));
    }

}
